package com.sinog.biz.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sinog.biz.mapper.havexml.PrisonerFxMapper;
import com.sinog.biz.mapper.havexml.PrisonersZyjnMapper;
import com.sinog.biz.mapper.havexml.XxblMapper;
import com.sinog.biz.service.business.XxblService;
import com.sinog.core.domain.PrisonerCjpg;
import com.sinog.core.domain.PrisonerFx;
import com.sinog.core.domain.PrisonersZyjn;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.util.PageReturnUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.IdGen;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc 信息补录service实现类
 * @author -
 * @date -
 */
@Service
public class XxblServiceImpl implements XxblService {

    @Resource
    private XxblMapper xxblMapper;
    @Resource
    private PrisonerFxMapper prisonerFxMapper;
    @Resource
    private PrisonersZyjnMapper prisonersZyjnMapper;

    /**
     * 衔接 - 信息补录 - 减刑假释信息录入保存
     * @param map map
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveJxjsInfo(Map<String,Object> map,UserDTO user) throws ParseException {
        //注意月份是MM
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String priStopTemp = map.get("priStop").toString();
        Date priStop = null;
        if(StringUtils.isNotEmpty(priStopTemp)) {
            //特别注意这个时间的转换
            priStop = simpleDateFormat.parse(map.get("priStop").toString());
        }
        //现刑期类型
        String subRange = (String)map.get("subRange");
        //服刑人员编号
        String priNum = (String)map.get("priNum");
        //上一次的刑期止日
        String priStopOld = (String)map.get("pristopold");
        //用户名
        String createUser = user.getUsername();
        //减刑假释表的id
        String id = IdGen.strid();
        //根据id选择fx数据对象
        Date date = new Date();
        PrisonerFx p = prisonerFxMapper.selectById((String)map.get("priNum"));
        Date priBegin = p.getPriBegin();
        if(ObjectUtils.allNotNull(priStop) && priBegin.after(priStop)) {
            return Result.failure(5000,"刑期止日不能小于刑期起日",null);
        }
        //保存减刑假释数据
        if(Constants.Number.NUM_ZERO < xxblMapper.saveJxjsInfo(id,subRange,priStop,priNum,createUser,priStopOld,date)) {
            int result = prisonerFxMapper.updatePriStopAndPritime(priNum,priStop,priStopOld,subRange,user.getAccount(),date);
            if(Constants.Number.NUM_ZERO < result) {
                return Result.success(ReturnCode.SUCCESS);
            } else {
                return Result.failure(ReturnCode.SAVE_FAILED);
            }
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 衔接 - 信息补录 - 减刑假释信息列表
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String jxjsInfoList(Integer pageIndex,Integer pageSize,String priNum) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page = page.setRecords(xxblMapper.jxjsInfoList(page,priNum));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 衔接 - 信息录入 - 减刑假释信息删除
     * @param priNum 罪犯编号
     * @param account 当前帐号
     * @return Result
     */
    @Override
    public Result jxjsInfoDelete(String priNum,@RequestParam String account) throws ParseException {
        //根据罪犯编号获取该罪犯最近的一条减刑假释信息
        Map<String,Object> jxjsInfo = xxblMapper.getJxjsInfo(priNum);
        //获取刑前刑期止日
        String pirStopOld = (String)jxjsInfo.get("priStopOld");
        String id = jxjsInfo.get("id").toString();
        //如果删除成功就更新一下fx表里的刑期止日
        if(0 < xxblMapper.jxjsInfoDelete(priNum,id)) {
            //将字符串格式化为日期
            Map<String,Object> lastJxjs = xxblMapper.getJxjsInfo(priNum);
            if(null == lastJxjs) {
                prisonerFxMapper.updatePriStopNow(priNum);
            } else {
                Date priStop = (Date)lastJxjs.get("priStop");
                Date date = new Date();
                //更新服刑表操作
                prisonerFxMapper.updatePriStopAndPritime(priNum,priStop,pirStopOld,(String)lastJxjs.get("subRange"),account,date);
            }
            return Result.success(ReturnCode.SUCCESS);
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 减刑假释信息刑期止日
     * @param priNum 罪犯编号
     * @return PrisonerFx
     */
    @Override
    public PrisonerFx selectJxjsPriStopInfo(String priNum) {
        return prisonerFxMapper.selectById(priNum);
    }

    /**
     * 衔接 - 信息补录 - 保存职业技能
     * @param data data
     * @param user user
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveZyjnInfo(String data,UserDTO user) {
        PrisonersZyjn prisonersZyjn = JsonUtil.toBean(data,PrisonersZyjn.class);
        //如果id为空则进行插入操作
        Date date = new Date();
        if(StringUtils.isBlank(prisonersZyjn.getId())) {
            //增加创建时间
            prisonersZyjn.setCreateTime(date);
            prisonersZyjn.setCreateUser(user.getAccount());
            prisonersZyjn.setUpdateUser(user.getAccount());
            prisonersZyjn.setUpdateTime(date);
            prisonersZyjn.setId(IdGen.strid());
            if(Constants.Number.NUM_ZERO < prisonersZyjnMapper.insert(prisonersZyjn)) {
                return Result.success(ReturnCode.SUCCESS);
            }
            //否则进行更新操作
        } else {
            prisonersZyjn.setUpdateUser(user.getAccount());
            prisonersZyjn.setUpdateTime(date);
            if(Constants.Number.NUM_ZERO < prisonersZyjnMapper.updateById(prisonersZyjn)) {
                return Result.success(ReturnCode.SUCCESS);
            }
        }
        return Result.failure(ReturnCode.SAVE_FAILED);
    }

    /**
     * 衔接 - 信息补录 - 职业技能信息列表
     * @param pageIndex pageIndex
     * @param pageSize pageSize
     * @param priNum 罪犯编号
     * @return String
     */
    @Override
    public String zyjnInfoList(Integer pageIndex,Integer pageSize,String priNum) {
        Page<Map<String,String>> page = new Page<>(pageIndex + 1,pageSize);
        page.setRecords(prisonersZyjnMapper.selectListByPriNum(page,priNum));
        return PageReturnUtil.pageReturn(page);
    }

    /**
     * 根据id查询职业技能
     * @param id id
     * @return PrisonersZyjn
     */
    @Override
    public PrisonersZyjn selectZyjnById(String id) {
        return prisonersZyjnMapper.selectById(id);
    }

    /**
     * 衔接 - 信息录入 - 职业技能信息删除
     * @param id id
     * @return int
     */
    @Override
    public int zyjnInfoDelete(String id) {
        return prisonersZyjnMapper.deleteById(id);
    }

    /**
     * 查询单条出监评估数据
     * @param priNum 罪犯编号
     * @return PrisonerCjpg
     */
    @Override
    public PrisonerCjpg selectCjpgInfoByPrNum(String priNum) {
        return prisonerFxMapper.selectCjpgInfoByPrNum(priNum);
    }

    /**
     * 安置帮教管理 - 帮教对象信息管理 - 全部人员管理 - 解除戒毒
     * @param jsonMap 业务数据
     * @return Result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateCjpg(Map<String,Object> jsonMap) {
        int cjpgState = prisonerFxMapper.updateCjpgInfoByPrNum(jsonMap);
        Map<String,Object> resultMap = new HashMap<>(16);
        resultMap.put("id",jsonMap.get("id"));
        if(Constants.Number.NUM_ZERO < cjpgState) {
            return Result.success(resultMap);
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 保存危险评估信息
     * @param data data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveWxxpgInfo(String data) {
        PrisonerFx prisonerFx = JsonUtil.toBean(data,PrisonerFx.class);
        //危险性评估信息更新
        int num = prisonerFxMapper.update(prisonerFx,new UpdateWrapper<PrisonerFx>().eq("pri_num",prisonerFx.getPriNum()));
        if(Constants.Number.NUM_ZERO < num) {
            return Result.success(num);
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 从prisoner_fx表获取罪犯刑期止日与刑期类型
     * @param priNum 罪犯编号
     * @return Result
     */
    @Override
    public Result getPrisonerFxInfo(String priNum) {
        PrisonerFx prisonerFx = prisonerFxMapper.getPrisonerFxInfo(priNum);
        if(null != prisonerFx) {
            return Result.success(prisonerFx);
        }
        return Result.failure(ReturnCode.FAILURE);
    }

    /**
     * 山西个性化需求
     * 预安置管理 - 预释放人员衔接 - 信息补录 - 服刑信息变更基本信息添加
     * @param jsonMap jsonMap
     * @return int
     */
    @Override
    public int updateJbxx(Map<String, Object> jsonMap) {
        PrisonerFx prisonerFx = JsonUtil.toBean(JsonUtil.toText(jsonMap), PrisonerFx.class);
        //1代表这个服刑人员已经死了，则需要设置死亡时间为null
        if(Constants.NumberStr.NUM_STR_TWO.equals(prisonerFx.getDeath())){
            prisonerFx.setDeathTime(null);
        }
        return prisonerFxMapper.update(prisonerFx, new QueryWrapper<PrisonerFx>().eq("pri_num", prisonerFx.getPriNum()));
    }
}